import React, { Component } from 'react';
import {
  Image, TouchableOpacity, View, Alert
} from 'react-native';
import ImagePickerGithub from 'react-native-image-picker';
import PropTypes from 'prop-types';
import { Toast } from 'antd-mobile-rn';
import Icon from 'react-native-vector-icons/Ionicons';
import AliyunOSS from 'aliyun-oss-react-native';
import { getOssToken } from '../model/app';
// import AliyunOSS, { bucketName, BaseDownUrl } from '../core/AliyunOSS';
import { UNIQUE_ID } from '../utils/deviceInfo';

const endPoint = 'oss-cn-beijing.aliyuncs.com';

AliyunOSS.enableDevMode();
const configuration = {
  maxRetryCount: 3,
  timeoutIntervalForRequest: 30,
  timeoutIntervalForResource: 24 * 60 * 60
};

export const bucketName = 'mxb-bucket';

export const BaseDownUrl = `https://${bucketName}.${endPoint}/`;

/**
 * 图片选择器
 *
 * @param {object[]} files - // 图片文件数组,元素为对象,包含属性 url（必选, 可能还有id, orientation, 以及业务需要的其它属性
 * @param {string} files[].url - // 图片的 url
 *
 * @param {boolean} selectable - 是否显示添加按钮
 * @param {object} containerStyle - 容器样式
 * @param {object} imageStyle - 单个图片样式
 * @param {object} selectButtonImageUrl - 上传按钮的背景图片
 * @param {number} max - 最大上传个数
 */
export default class ImagePicker extends Component {
  static propTypes = {
    files: PropTypes.array,
    selectable: PropTypes.bool,
    containerStyle: PropTypes.object,
    // change: PropTypes.funs,
    objectKey: PropTypes.string,
    selectButtonImageUrl: PropTypes.string,
    max: PropTypes.number,
    deletable: PropTypes.bool
  };

  static defaultProps = {
    files: [],
    selectable: false,
    containerStyle: {},
    imageStyle: {},
    selectButtonImageUrl: '',
    deletable: false,
    max: Number.NEGATIVE_INFINITY
  };

  async asyncUpload({ url, objectKey }) {
    const { change, files } = this.props;
    Toast.loading('上传中...', 0);
    console.log('bucketName', bucketName);
    console.log('objectKey', objectKey);
    console.log('url', url);
    const {
      dataObject: { securityToken, accessKeyId, accessKeySecret }
    } = await getOssToken();
    // console.log(res);
    // AliyunOSS.initWithSecurityToken(
    //   'CAIS/wF1q6Ft5B2yfSjIr4veDfmD2JR0x4y8dX/L1ngWPb5u2vbbpzz2IHBEeXNgBO4Ytfs/n25T5/0dlqp6U4cdgM8u2Wg0vPpt6gqET9fria7ctM456vCMHWyUFGSMvqv7aPn4S9XwY+qkb0u++AZ43br9c0fNPTGiKobby+QkDLItUxK/cCBNCfpPOwJms7V6D3bKMuu3OROY5Qi1BUFz6A1nkjE9u+btgO/ks0OC3QGgm7NM99ytfMT5MPMBZskvD42Hu8VtbbfE3SJq7BxHybx7lqQs+02c7oHAWQkMvUvdbLqPrIY+d1BjA68hAOtKsfz40Od/vuHDBgs/ApiJ0IsagAElP1mQtkopQq5LKVEU2cFoi3pS+feMsAmUOa3Xpc4CJZOP+cLDpw9HyHeUOKzDMJPfF1VqtZqztGz4HSBe88PZ9RHPkdizHv+70/fgSDO/RH9ip+enipMVb4p9UasqgbG79xOuaHcO5kCvHJyGmqodtxh5ACyUOxBgO5QS3XgWdA==',
    //   'STS.NHkFC75KUpNWwYz2xC11B53pE',
    //   '29M1TWM2ujSVGvo1HteN1bcDYyFJPrSvMKFKrRQfXt44',
    //   endPoint,
    //   configuration
    // );
    AliyunOSS.initWithSecurityToken(
      securityToken,
      accessKeyId,
      accessKeySecret,
      endPoint,
      configuration
    );
    AliyunOSS.asyncUpload(bucketName, objectKey, url)
      .then((res) => {
        change
          && change(
            [
              ...files,
              {
                url: `${BaseDownUrl}${objectKey}`
              }
            ],
            res
          );
        Toast.hide();
      })
      .catch((e) => {
        console.log(e);
        Toast.fail('上传失败!');
      });
    // AliyunOSS.addEventListener('uploadProgress', (p) => {
    //   console.log('here？');
    //   // const per = parseInt(p.currentSize / p.totalSize * 10);
    //   // if (per !== logCount) {
    //   //   logCount = per;
    //   //   JLLog(`uploadProgress ${per}`);
    //   // }
    // });
  }

  selectPhotoTapped() {
    const options = {
      title: '',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍摄',
      chooseFromLibraryButtonTitle: '从手机相册选择',
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,
      storageOptions: {
        skipBackup: true
      }
    };

    ImagePickerGithub.showImagePicker(options, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled photo picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        READ_CACHE('userInfo')
          .then((ret) => {
            // console.log(ret);
            const objectKey = `${ret.mobile}/${UNIQUE_ID}${+new Date()}${response.fileSize}${
              response.fileName
            }`;
            // const objectKey = 'aaa';
            // const objectKey = `${ret.userId}/${UNIQUE_ID}${+new Date()}${response.fileSize}${
            //   response.fileName
            // }`;
            this.asyncUpload({ url: response.uri, objectKey });
          })
          .catch(() => {
            // 未注册用户
            const objectKey = `_unregistered/${UNIQUE_ID}${+new Date()}${response.fileSize}${
              response.fileName
            }`;
            this.asyncUpload({ url: response.uri, objectKey });
          });

        // You can also display the image using data:
        // let source = { uri: 'data:image/jpeg;base64,' + response.data };
      }
    });
  }

  deleteImage(index) {
    const { files, change } = this.props;
    files.splice(index, 1);
    change(files);
  }

  longPressImage(index) {
    Alert.alert(
      '确认删除图片？',
      '',
      [{ text: '取消', style: 'cancel' }, { text: '删除', onPress: () => this.deleteImage(index) }],
      { cancelable: false }
    );
  }

  renderImage({ url, index }) {
    const { imageStyle, deletable } = this.props;

    return (
      <TouchableOpacity key={url} onLongPress={() => deletable && this.longPressImage(index)}>
        <Image
          style={{
            ...styles.imageStyle,
            ...imageStyle
          }}
          source={{ uri: url }}
          key={url}
        />
      </TouchableOpacity>
    );
  }

  renderImageLikeButton() {
    const { imageStyle, selectButtonImageUrl } = this.props;
    return (
      <Image
        style={{
          ...styles.imageStyle,
          ...imageStyle
        }}
        source={{ uri: selectButtonImageUrl }}
      />
    );
  }

  renderViewLikeButton() {
    const { imageStyle } = this.props;
    return (
      <View
        style={{
          justifyContent: 'center',
          alignItems: 'center',
          ...styles.imageStyle,
          ...imageStyle
        }}
      >
        <Icon name="md-add" size={24} />
      </View>
    );
  }

  renderSelectableButton() {
    const {
      imageStyle, // 图片的style样式
      selectButtonImageUrl
    } = this.props;
    return (
      <TouchableOpacity
        style={{
          ...styles.imageStyle,
          ...imageStyle
        }}
        onPress={() => this.selectPhotoTapped()}
      >
        {selectButtonImageUrl === '' ? this.renderViewLikeButton() : this.renderImageLikeButton()}
      </TouchableOpacity>
    );
  }

  render() {
    const {
      files,
      containerStyle, // 容器style样式
      selectable,
      max
    } = this.props;

    return (
      <View
        style={{
          flexDirection: 'row',
          flexWrap: 'wrap',
          justifyContent: 'flex-start',
          ...containerStyle
        }}
      >
        {files && files.map((item, index) => this.renderImage({ url: item.url || '', index }))}
        {selectable && files.length < max && this.renderSelectableButton()}
      </View>
    );
  }
}

const styles = {
  imageStyle: {
    width: SCALE(160),
    height: SCALE(160),
    marginRight: SCALE(16),
    backgroundColor: '#f9f9f9',
    marginBottom: SCALE(16)
  }
};
